package com.xianggu.trafficLimiter.impl;

import com.xianggu.redis.RedisConnection;
import com.xianggu.trafficLimiter.TrafficLimiter;

import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author chengjy
 * @date 2025/3/25
 */

public class RedisBucketLimiter implements TrafficLimiter {
    private long max = 10; // 每秒中最大QBS

    private int interval = 1000; // 时间窗口时长

    public static RedisConnection redis;

    private SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
    public RedisBucketLimiter() {
        redis = new RedisConnection("192.168.80.130", 6379);
    }

    @Override
    public boolean limit() {
        // 对当前的时间秒单为进行自增，如果结果超过最大值表示达到了阈值
        String key = format.format(System.currentTimeMillis());
        if (redis.incrWithExpire(key, interval) > max) {
            return true;
        }
        return false;
    }
}
